const Controller = require('egg').Controller;


class wxOrder extends Controller {

    async add(){
        const {app,ctx,service} = this;
        var uuid = require('node-uuid');
        const {id,orderDate,shopCarts,total,address_id,radio} = ctx.request.body;
        //开启事务
        let t = await ctx.model.transaction();
        try {
            //调用sequelize update更新为批量更新 只要满足where条件的数据都将被更新
            let user = await ctx.model.FdUser.findOne({where:{id},transaction:t,lock:t.LOCK.UPDATE});
            if(parseFloat(user.money) < parseInt(total)){
                throw new Error('余额不足');
                return;
            }
            user.money = user.money - parseFloat(total);
            user.save({transaction:t});
            let order = {
                deleted:'0',
                id:uuid.v1(),
                user_id:id,
                address_id,
                status:'0',
                is_reservation:'0'
            }
            if(radio == '2'){
                order = {
                    ...order,
                    is_reservation:'1',
                    reservation_at:orderDate
                }
            }
            let rs = await ctx.model.FdOrder.create(order,{transaction:t});

            let array = [];
            for (let i = 0; i < shopCarts.length; i++) {
                let shopCart = shopCarts[i];
                let order_list = {
                    id:uuid.v1(),
                    order_id:order.id,
                    type_id:shopCart.closeItem.id,
                    color:shopCart.close.color,
                    num:shopCart.close.num,
                    price:parseInt(shopCart.close.num) * parseFloat(shopCart.closeItem.price),
                    pic:shopCart.close.pic,
                    remark:shopCart.close.remark
                }
                array.push(order_list);
            }
            let rss = await ctx.model.FdOrderList.bulkCreate(array,{transaction:t});

            //提交事务
            t.commit();
        }catch (e) {
            //失败回滚
            t.rollback();
            //抛出错误信息
            ctx.throw(500,e.message)
        }

        ctx.body = {
            code : 200,
            data : {},
            msg : ''
        }
    }

    async getIngList(){
        const {app,ctx,service} = this;
        const {id} = ctx.request.query;
        let sql = `
        select
        a.id,c.realname,c.province,c.address,a.status,DATE_FORMAT(a.created_at,'%Y-%m-%d %H:%i') as created_at,a.is_complaint,d.name,b.num,b.price
        from fd_order a
        left join fd_order_list b on b.order_id = a.id
        left join fd_type d on d.id = b.type_id
        left join fd_address c on c.id = a.address_id
        where a.user_id = '${id}' and a.status not in ('12','11','13')
        group by a.id
        order by a.created_at desc
        `;
        const sequelize_query_param = {raw:true,type:app.Sequelize.QueryTypes.SELECT};
        let data = await ctx.model.query(sql,sequelize_query_param);
        ctx.body = {
            code : 200,
            data : data,
            msg : ''
        }
    }

    async getDoneList(){
        const {app,ctx,service} = this;
        const {id} = ctx.request.query;
        let sql = `
        select
        a.id,c.realname,c.province,c.address,a.status,DATE_FORMAT(a.created_at,'%Y-%m-%d %H:%i') as created_at,a.is_complaint,d.name,b.num,b.price
        from fd_order a
        left join fd_order_list b on b.order_id = a.id
        left join fd_type d on d.id = b.type_id
        left join fd_address c on c.id = a.address_id
        where a.user_id = '${id}' and a.status in ('12','13','11')
        group by a.id
        order by a.created_at desc
        `;
        const sequelize_query_param = {raw:true,type:app.Sequelize.QueryTypes.SELECT};
        let data = await ctx.model.query(sql,sequelize_query_param);
        ctx.body = {
            code : 200,
            data : data,
            msg : ''
        }
    }

    async complaint(){
        const {app,ctx,service} = this;
        const {id,content,pic} = ctx.request.body;
        //开启事务
        let t = await ctx.model.transaction();
        try {
            let order = await ctx.model.FdOrder.findOne({where:{id},transaction:t,lock:t.LOCK.UPDATE});
            order.is_complaint = '1',
                order.complaint = content,
                order.complaint_pic = pic;
            await order.save({transaction:t});
            //提交事务
            t.commit();
        }catch (e) {
            //失败回滚
            t.rollback();
            //抛出错误信息
            ctx.throw(500,e.message)
        }
        ctx.body = {
            code : 200,
            data : {},
            msg : ''
        }
    }

    async confirm(){
        const {app,ctx,service} = this;
        const {id,rate,content,pic} = ctx.request.body;
        //开启事务
        let t = await ctx.model.transaction();
        try {
            let order = await ctx.model.FdOrder.findOne({where:{id},transaction:t,lock:t.LOCK.UPDATE});
            order.status = '12',
                order.rete = rate,
                order.evaluation = content,
                order.evaluation_pic = pic;
            if(!app.lodash.isEmpty(order.staff_id)){
                service.rechargeService.rechargeById(order.staff_id,5);
            }
            await order.save({transaction:t});
            //提交事务
            t.commit();
        }catch (e) {
            //失败回滚
            t.rollback();
            //抛出错误信息
            ctx.throw(500,e.message)
        }
        ctx.body = {
            code : 200,
            data : {},
            msg : ''
        }
    }

    async orderDetail(){
        const {app,ctx,service} = this;
        const {id} = ctx.request.query;
        let sql  = `
        select
        a.id,a.number,c.realname,c.province,c.address,c.phone,a.status,a.created_at,a.is_complaint,a.complaint,a.complaint_pic,a.replay,a.replay_pic,a.rete,a.evaluation,a.evaluation_pic,e.realname as staffname,f.name as storename,e.phone as staffphone
        from fd_order a
        left join fd_address c on c.id = a.address_id
        left join fd_user e on e.id = a.staff_id
        left join fd_store f on f.id = a.store_id
        where a.id = '${id}'
        `;
        const sequelize_query_param = {raw:true,type:app.Sequelize.QueryTypes.SELECT};
        let order = await ctx.model.query(sql,sequelize_query_param);
        order = order[0];

        sql = `
        select a.num,b.name,a.price
        from fd_order_list a
        left join fd_type b on b.id = a.type_id
        where a.deleted = '0' and a.order_id = '${id}'
        `;
        let orderList = await ctx.model.query(sql,sequelize_query_param);

        order.list = orderList;

        order.complaint_pic = order.complaint_pic == null ? []:order.complaint_pic.split(',');
        order.replay_pic = order.replay_pic == null ? []:order.replay_pic.split(',');
        order.evaluation_pic = order.evaluation_pic == null ? []:order.evaluation_pic.split(',');

        //返回
        ctx.body = {
            code : 200,
            data : order,
            msg : ''
        }
    }

    async staffOrderList(){
        const {app,ctx,service} = this;
        const {id} = ctx.request.query;
        let staff = await ctx.model.FdUser.findOne({where:{id}});
        let sql = `
        select
        a.id,c.realname,c.province,c.address,a.status,DATE_FORMAT(a.created_at,'%Y-%m-%d %H:%i') as created_at,a.is_complaint,a.number as order_num
        from fd_order a
        left join fd_address c on c.id = a.address_id
        where a.store_id = '${staff.belong_id}' and a.status = '1' and a.deleted = '0'
        order by a.created_at desc
        `;
        const sequelize_query_param = {raw:true,type:app.Sequelize.QueryTypes.SELECT};
        let data = await ctx.model.query(sql,sequelize_query_param);
        // let data = await ctx.model.FdOrder.findAndCount({where:{store_id:staff.belong_id,deleted:'0',status:'1'}});
        ctx.body = {
            code : 200,
            data : {rows:data},
            msg : ''
        }
    }

    async staffIngOrderList(){
        const {app,ctx,service} = this;
        const {id} = ctx.request.query;
        const Op = app.Sequelize.Op;
        let sql = `
        select
        a.id,c.realname,c.province,c.address,a.status,DATE_FORMAT(a.created_at,'%Y-%m-%d %H:%i') as created_at,a.is_complaint,a.number as order_num,c.phone
        from fd_order a
        left join fd_address c on c.id = a.address_id
        where a.staff_id = '${id}' and a.status not in ('0','1','11','12','13') and a.deleted = '0'
        order by a.created_at desc
        `;
        const sequelize_query_param = {raw:true,type:app.Sequelize.QueryTypes.SELECT};
        let data = await ctx.model.query(sql,sequelize_query_param);
        // let data = await ctx.model.FdOrder.findAndCount({where:{staff_id:id,deleted:'0',status:{[Op.notIn]:['0','1','12','13']}}});
        ctx.body = {
            code : 200,
            data : {rows:data},
            msg : ''
        }
    }

    async staffDoneOrderList(){
        const {app,ctx,service} = this;
        const {id} = ctx.request.query;
        const Op = app.Sequelize.Op;
        let sql = `
        select
        a.id,c.realname,c.province,c.address,a.status,DATE_FORMAT(a.created_at,'%Y-%m-%d %H:%i') as created_at,a.is_complaint,a.number as order_num,c.phone
        from fd_order a
        left join fd_address c on c.id = a.address_id
        where a.staff_id = '${id}' and a.deleted = '0'
        order by a.status desc, a.created_at desc
        `;
        const sequelize_query_param = {raw:true,type:app.Sequelize.QueryTypes.SELECT};
        let data = await ctx.model.query(sql,sequelize_query_param);
        // let data = await ctx.model.FdOrder.findAndCount({where:{staff_id:id,deleted:'0',status:{[Op.notIn]:['0','1','12','13']}}});
        ctx.body = {
            code : 200,
            data : {rows:data},
            msg : ''
        }
    }

    async grap(){
        const {app,ctx,service} = this;
        const {user_id,order_id} = ctx.request.body;
        let t;
        const Op = app.Sequelize.Op;
        try{
            t = await ctx.model.transaction();
            let order = await ctx.model.FdOrder.findOne({where:{id:order_id,status:'1'},transaction:t,lock:t.LOCK.UPDATE});
            let rows = await ctx.model.FdOrder.findAll({where:{staff_id: user_id,status:{[Op.notIn]:['11','12','13']}},transaction:t});
            if(rows.length > 0){
                ctx.throw(401,'当前还有订单为完结，无法接收新的订单')
            }
            order.staff_id = user_id;
            order.status = '2';
            await order.save({transaction:t});
            t.commit();
            ctx.body = {
                code : 200,
                data : {},
                msg : ''
            }
        }catch (e) {
            t.rollback();
            ctx.throw(401,e.message)
        }
    }

    /**
     * 工作人员改变订单状态
     * @returns {Promise<void>}
     */
    async staffOrderProcess(){
        const {app,ctx,service} = this;
        const {order_id,staff_id,status,pic} = ctx.request.body;
        //创建规则
        const rule = {
            order_id:'required',
            staff_id:'required',
            status:'required',
            pic:'required',
        };
        //验证
        const err = await app.validator.validate(ctx.request.body,rule);
        //判断验证结果
        if(!app.lodash.isEmpty(err)){
            //抛出验证错误
            ctx.throw(401,err[0].field+' -- '+err[0].message);
        }

        let t;
        const Op = app.Sequelize.Op;
        try{
            t = await ctx.model.transaction();
            let order = await ctx.model.FdOrder.findOne({where:{id:order_id},transaction:t,lock:t.LOCK.UPDATE});

            if(parseInt(order.status)>=parseInt(status)){
                ctx.throw(401,'当前订单状态异常，请刷新重试');
            }
            order.status = status;
            await order.save({transaction:t});
            ctx.logger.info('订单状态改变：',JSON.stringify({staff_id:staff_id,order_id:order_id,status:status,pics:pic}));
            t.commit();
            ctx.body = {
                code : 200,
                data : {},
                msg : ''
            }
        }catch (e) {
            t.rollback();
            ctx.throw(401,e.message)
        }
    }

    async centerOrderList(){
        const {app,ctx,service} = this;
        const {id} = ctx.request.query;
        let staff = await ctx.model.FdUser.findOne({where:{id}});
        let sql = `
        select
        a.id,c.realname,c.province,c.address,a.status,DATE_FORMAT(a.created_at,'%Y-%m-%d %H:%i') as created_at,a.is_complaint,a.number as order_num
        from fd_order a
        left join fd_address c on c.id = a.address_id
        left join fd_store b on b.id = a.store_id
        where b.center_id = '${staff.belong_id}' and a.status in ('4','5','6','7') and a.deleted = '0'
        order by a.status desc,a.created_at desc
        `;
        const sequelize_query_param = {raw:true,type:app.Sequelize.QueryTypes.SELECT};
        let data = await ctx.model.query(sql,sequelize_query_param);
        // let data = await ctx.model.FdOrder.findAndCount({where:{store_id:staff.belong_id,deleted:'0',status:'5'}});
        ctx.body = {
            code : 200,
            data : {rows:data},
            msg : ''
        }
    }

    async centerDoneOrderList(){
        const {app,ctx,service} = this;
        const {id} = ctx.request.query;
        const Op = app.Sequelize.Op;
        let staff = await ctx.model.FdUser.findOne({where:{id}});
        let sql = `
        select
        a.id,c.realname,c.province,c.address,a.status,DATE_FORMAT(a.created_at,'%Y-%m-%d %H:%i') as created_at,a.is_complaint,a.number as order_num,c.phone
        from fd_order a
        left join fd_address c on c.id = a.address_id
        left join fd_store b on b.id = a.store_id
        where b.center_id = '${staff.belong_id}' and a.deleted = '0'
        order by a.status desc, a.created_at desc
        `;
        const sequelize_query_param = {raw:true,type:app.Sequelize.QueryTypes.SELECT};
        let data = await ctx.model.query(sql,sequelize_query_param);
        // let data = await ctx.model.FdOrder.findAndCount({where:{staff_id:id,deleted:'0',status:{[Op.notIn]:['0','1','12','13']}}});
        ctx.body = {
            code : 200,
            data : {rows:data},
            msg : ''
        }
    }




}

module.exports = wxOrder;
